<template>
  <div>
    <a-card class="card" :bordered="false" :style="`min-height: ${cardMinHeight}px;`">

      <!--选择没有被加入task的计划-->
      <a-modal
          destroyOnClose
          class="addModal"
          v-model='addModal'
          width='1100px'
          :title="isAdd?'新增任务':title"
          @ok="submit"
          @cancel="handleCancel0"
          :bodyStyle="bodyStyle"
      >
        <a-spin :spinning="spinning">
          <div style="width: 100%;min-height: 30px;display: flex;flex-direction: row;padding: 10px 24px 10px 24px;justify-content: space-between">
            <div style="width: 85%;">
              <a-form-model layout="inline">
                <a-form-model-item
                    label="计划单号"
                    ref="dateRef"
                >
                  <a-input style='width: 200px;height: 32px' v-model='queryForm2.planCode' @keydown.enter="filter2" @change="filter2" v-auth="`query`"></a-input>
                </a-form-model-item>

                <a-form-model-item
                    label="日期范围"
                >
                  <a-range-picker
                      :valueFormat="'YYYY-MM-DD'"
                      @keydown.enter="filter2"
                      @change="filter2"
                      :format="'YYYY-MM-DD'"
                      v-model.trim="queryForm2.dateSelect"
                      :allow-clear="true"/>
                </a-form-model-item>

                <a-form-model-item>
                  <a-button type='primary' style='height: 32px;width: 70px;text-align: center' @click="reset2" v-auth="`query`">
                    重置
                  </a-button>
                </a-form-model-item>

              </a-form-model>

            </div>
          </div>
          <!--标签页-->
          <div style="width: 100%;min-height: 250px;display: flex;flex-direction: row;padding: 10px 24px 0px 24px;border-top: 1px solid #ddd;">
            <a-table
                :columns="key1Columns"
                :data-source="key1Data"
                :pagination="key1Pagination"
                @change="onChangeKey1"
                :showPagination="true"
                style="width: 100%;"
                :loading="tableLoading01"
                :rowKey="(record1) => {return record1.index}"
                :scroll="{x:true,y: 300 }"
            >
              <template slot="action" slot-scope="record1">
                  <a @click="addDetail(record1)">详情</a>
              </template>
            </a-table>
          </div>
        </a-spin>

      </a-modal>

    <!--task详情界面-->
      <a-modal
          destroyOnClose
          v-model='addDetailModal'
          width='1400px'
          :title="isAdd?'新增任务详情':title"
          @cancel="handleCancelDetail"
          @ok="submitAddTask"

          :bodyStyle="bodyStyle"
      >
        <a-spin :spinning="spinning">
          <!--标签页-->
          <div style="width: 100%;min-height: 250px;display: flex;flex-direction: row;padding: 10px 24px 0px 24px;">
            <a-table
                :columns="key1ColumnsDetail"
                :data-source="key1DataDetail"
                :pagination="key1PaginationDetail"
                @change="onChangeKey1Detail"
                :showPagination="true"
                style="width: 100%;"
                :loading="tableLoading01Detail"
                :scroll="{x:true,y: 300 }"
            >
              <template slot="action1" slot-scope="record1">
                <a-input style='width: 100px;height: 32px'
                         v-model.trim="record1.task_code"

                         v-auth="`query`" ></a-input>
              </template>
              <template slot="action0" slot-scope="record1">
                <a-popover  trigger="click" placement="bottom" :overlayStyle="{ width: '100px' }">
                  <template slot="content">
                    <p class="aPopover" v-for="(item,index) in userSearchList" :key="index"  @click="changeUser(item,record1)" >{{item.name}}</p>
                  </template>
                <a-input style='width: 100px;height: 32px'
                         v-model.trim="record1.order_user"
                         allowClear
                         @keydown.enter="getUserList(record1.order_user)"
                         @change="getUserList(record1.order_user)"
                         @click="getUserList(record1.order_user)"
                          v-auth="`query`" ></a-input>
                </a-popover>
              </template>
              <template slot="action" slot-scope="record1">
                <a>删除</a>
              </template>
            </a-table>
          </div>
        </a-spin>

      </a-modal>

    <!--  详情    -->
      <a-modal
          destroyOnClose
          v-model='detailModal'
          width='800px'
          :title="canBeQuery?'详情':title"
          :bodyStyle="bodyStyle"
          @cancel="detailCancel"
          @ok="detailCancel"
      >
        <a-spin :spinning="spinning">
          <div style="width: 100%;min-height: 30px;display: flex;flex-direction: row;padding: 10px 24px 10px 24px;justify-content: space-between">
            <div style="width: 95%;">
              <a-form-model   layout="inline" >
                <a-form-model-item
                    label="任务编码"
                    style="margin-left: 30px">
                  <a-input style='width: 200px;height: 32px;' v-model.trim="record.code" :disabled="!canBeEdited || !isAdd"></a-input>
                </a-form-model-item>
                <a-form-model-item
                    label="设备"
                    style="margin-left: 72px">
                  <a-input style='width: 200px;height: 32px;' v-model.trim="record.device_name" :disabled="!canBeEdited || !isAdd"></a-input>
                </a-form-model-item>
                <a-form-model-item
                    label="预计用时"
                    style="margin-left: 30px">
                  <a-input style='width: 200px;height: 32px;' v-model.trim="record.expect_time" :disabled="!canBeEdited || !isAdd"></a-input>
                </a-form-model-item>
                <a-form-model-item
                    label="保养责任人"
                    style="margin-left: 30px">

                  <a-input style='width: 200px;height: 32px;' v-model.trim="record.maintenance_person_name"
                           :disabled="!canBeEdited || !isAdd"></a-input>

                </a-form-model-item>

                <a-form-model-item
                    label="保养状态"
                    style="margin-left: 30px">
                  <a-input style='width: 200px;height: 32px;' v-model.trim="record.maintenance_status_name" :disabled="!canBeEdited || !isAdd"></a-input>
                </a-form-model-item>

                <a-form-model-item
                    label="保养时间"
                    style="margin-left: 44px">
                  <a-input style='width: 200px;height: 32px;' v-model.trim="record.maintenance_time" :disabled="!canBeEdited || !isAdd"></a-input>
                </a-form-model-item>
                <a-form-model-item
                    label="保养类别"
                    style="margin-left: 30px">
                  <a-input style='width: 200px;height: 32px;' v-model.trim="record.maintenance_type_name" :disabled="!canBeEdited || !isAdd"></a-input>
                </a-form-model-item>
                <a-form-model-item
                    label="实际用时"
                    style="margin-left: 44px">
                  <a-input style='width: 200px;height: 32px;' v-model.trim="record.real_cost_time" :disabled="!canBeEdited || !isAdd"></a-input>
                </a-form-model-item>
              </a-form-model>

            </div>
          </div>
        </a-spin>

      </a-modal>

      <!--任务调整-->
      <a-modal
          destroyOnClose
          v-model='remodelModal'
          width='800px'
          :title="canBeQuery?'任务调整':title"
          :bodyStyle="bodyStyle"
          @cancel="taskCancel"
          @ok="saveTask"
      >
        <a-spin :spinning="spinning">
          <div style="width: 100%;min-height: 30px;display: flex;flex-direction: row;padding: 10px 24px 10px 24px;justify-content: space-between">
            <div style="width: 95%;">
              <a-form-model   layout="inline" >
                <a-form-model-item
                    label="任务编码"
                    style="margin-left: 30px">
                  <a-input style='width: 200px;height: 32px;' v-model.trim="record.code" disabled></a-input>
                </a-form-model-item>
                <a-form-model-item
                    label="设备"
                    style="margin-left: 72px">
                  <a-input style='width: 200px;height: 32px;' v-model.trim="record.device_name" disabled></a-input>
                </a-form-model-item>
                <a-form-model-item
                    label="预计用时"
                    style="margin-left: 30px">
                  <a-input style='width: 200px;height: 32px;' v-model.trim="record.expect_time" disabled></a-input>
                </a-form-model-item>
                <a-form-model-item
                    label="保养责任人"
                    style="margin-left: 30px">
                  <a-popover  trigger="focus" placement="bottom" :overlayStyle="{ width: '200px' }">
                    <template slot="content">
                      <p class="aPopover" v-for="(item,index) in userSearchList" :key="index"  @click="changeUser2(item)" >{{item.name}}</p>
                    </template>
                  <a-input style='width: 200px;height: 32px;' v-model.trim="record.maintenance_person_name"
                           @keydown.enter="getUserList(record.maintenance_person_name)"
                           @change="getUserList(record.maintenance_person_name)"
                           @click="getUserList(record.maintenance_person_name)"
                           allowClear
                           :disabled="!canBeEdited || !isAdd"></a-input>
                  </a-popover>
                </a-form-model-item>

                <a-form-model-item
                    label="保养状态"
                    style="margin-left: 30px">
                  <a-input style='width: 200px;height: 32px;' v-model.trim="record.maintenance_status_name" disabled></a-input>
                </a-form-model-item>

                <a-form-model-item
                    label="保养时间"
                    style="margin-left: 44px">
                  <a-input style='width: 200px;height: 32px;' v-model.trim="record.maintenance_time" disabled></a-input>
                </a-form-model-item>
                <a-form-model-item
                    label="保养类别"
                    style="margin-left: 30px">
                  <a-input style='width: 200px;height: 32px;' v-model.trim="record.maintenance_type_name" disabled></a-input>
                </a-form-model-item>
              </a-form-model>

            </div>
          </div>
        </a-spin>

      </a-modal>

      <page-head-area>
        <div class="extra" style="width: 260px;display: flex;justify-content: space-around">
<!--          <a-badge count="9">-->
            <a-button icon="plus-circle" v-auth="`insert`" @click="add" style="background-color: #fff;border: none;margin-left: 10px;width: 70px;height: 35px;">新增</a-button>
<!--          </a-badge>-->
          <a-popconfirm
              title="确定删除吗?"
              ok-text="确定"
              cancel-text="取消"
              @confirm="deleteSelectTask"
          >
          <a-button icon="delete" v-auth="`delete`" style="background-color: #fff;border: none;margin-left: 10px;width: 70px;height: 35px;">删除</a-button>
          </a-popconfirm>
          <a-button icon="audit"  style="background-color: #fff;border: none;margin-left: 10px;width: 70px;height: 35px;">审核</a-button>
        </div>
      </page-head-area>

      <div class="queryBox">
        <a-form-model layout="inline" :model='queryForm' ref="queryFormRef" class='query' style='display: flex;flex-wrap: wrap;'>
          <a-form-model-item
              label="编码"
              style="margin-left: 0px"
          >
            <a-input style='width: 200px;height: 32px' v-model='queryForm.code' v-auth="`query`"></a-input>
          </a-form-model-item>
          <a-form-model-item
              class='optionTitle'
              label="名称"
          >
            <a-input style='width: 200px;height: 32px' v-model='queryForm.name' v-auth="`query`"></a-input>
          </a-form-model-item>


          <a-form-model-item
              label="状态"
          >
            <a-select
                show-search
                style='width: 150px'
                v-model.trim='queryForm.status'
                v-auth="`query`"
            >
              <a-select-option
                  v-for='item in taskStatusList'
                  :key='item.code'
                  :value='item.code'
              >{{item.description}}</a-select-option>
            </a-select>
          </a-form-model-item>

          <a-form-model-item
              label="日期范围"
          >
            <a-range-picker
                :valueFormat="'YYYY-MM-DD'"
                :format="'YYYY-MM-DD'"
                v-model.trim="queryForm.dateSelect"
                :allow-clear="true"/>
          </a-form-model-item>

          <a-form-model-item>
            <a-button type='primary' style='height: 32px;width: 70px;text-align: center' @click="reset" v-auth="`query`">
              重置
            </a-button>
          </a-form-model-item>
          <a-form-model-item>
            <a-button type='primary' style='height: 32px;width: 70px;text-align: center' @click="filter" v-auth="`query`">
              搜索
            </a-button>
          </a-form-model-item>
        </a-form-model>
      </div>
      <div class="dataBox">
        <a-table
            :columns="columns"
            :data-source="data"
            :pagination="false"
            :loading="tableLoading"
            :rowKey="(recordS) => {return recordS.id}"
            :scroll="{ x: 1000, y: 500 }"
            :row-selection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
        >
          <template slot="action" slot-scope="record">
            <div v-if="record.status===1">
              <a v-auth="`query`" @click="detail(record)">详情</a>
            </div>

            <div v-if="record.status===0">
              <a v-auth="`update`" @click="remodel(record)">任务调整</a>
              <a-divider type="vertical"/>
              <a-popconfirm title="确定删除?" @confirm="() => deleteTask(record)">
              <a v-auth="`delete`" >删除</a>
              </a-popconfirm>
            </div>

          </template>
        </a-table>

      </div>

      <a-pagination
          @change="onChangePage"
          @showSizeChange="showSizeChange"
          :total="pagination.total"
          :showSizeChanger="true"
          :showQuickJumper="true"
          :defaultPageSize="pagination.defaultPageSize"
          :pageSize="pagination.page_size"
          :pageSizeOptions="pagination.pageSizeOptions"
          :current="pagination.current"
          :showTotal="pagination.showTotal"
          style="width: 100%;display: flex;flex-direction: row;justify-content: flex-end;margin-top: 15px"
      ></a-pagination>
    </a-card>
  </div>
</template>

<script>

import {mapGetters} from "vuex";
import PageHeadArea from "../module/pageHeadArea.vue";
import pagination from "ant-design-vue/lib/pagination";
import storage from "store";
import {DEPT_ID, ORGANIZATION_ID, USER_TOKEN} from "@/store/mutation-types";
import axios from "axios";

import {
  deleteDevice,
  deleteDeviceMaintenanceTask,
  getCacheByVaguename,
  getDeviceList, getDeviceMaintenancePlanList,
  getDeviceMaintenanceTypeList,
  getMaintenancePlanDeviceRelationList, getUserNameById,
  listDeviceMaintenanceTaskAll, saveDeviceMaintenanceTask
} from "../../utils/interface";
import {message} from "ant-design-vue";
import {list_device_maintenance_task_all} from "../../services/deviceMaintenance";

const key1DataDetail = []
const key1ColumnsDetail = [
  { title: '序号', width: 120, align:'center',dataIndex: 'id', key: 'id'},
  { title: '编码', width: 120, align:'center',dataIndex: 'device_code', key: 'device_code'},
  { title: '名称', width: 120, align:'center',dataIndex: 'device_name', key: 'device_name'},
  { title: '保养日期', width: 120, align:'center',dataIndex: 'maintenance_time', key: 'maintenance_time'},
  { title: '保养类别', width: 120, align:'center',dataIndex: 'maintenance_type_name', key: 'maintenance_type_name'},
  { title: '保养类别', width: 120, align:'center',dataIndex: 'maintenance_type_name', key: 'maintenance_type_name'},
  { title: '预计用时(h)', width: 120, align:'center',dataIndex: 'expect_time', key: 'expect_time'},
  {
    title: '任务编码',
    align:'center',
    key: 'operation',
    fixed: 'right',
    width: 120,
    scopedSlots: { customRender: 'action1' }
  },
  {
    title: '分配任务',
    align:'center',
    key: 'operation',
    fixed: 'right',
    width: 120,
    scopedSlots: { customRender: 'action0' }
  },
  {
    title: '操作',
    align:'center',
    key: 'operation',
    fixed: 'right',
    width: 180,
    scopedSlots: { customRender: 'action' }
  }
]
const data = []
const columns = [
  { title: '任务单号', width: 120, align:'center',dataIndex: 'code', key: 'code'},
  { title: '设备编码', width: 120, align:'center',dataIndex: 'device_code', key: 'device_code'},
  { title: '设备名称', width: 120, align:'center',dataIndex: 'device_name', key: 'device_name'},
  { title: '保养日期', width: 120, align:'center',dataIndex: 'maintenance_time', key: 'maintenance_time'},
  { title: '保养类别', width: 120, align:'center',dataIndex: 'maintenance_type_name', key: 'maintenance_type_name'},
  { title: '状态', width: 120, align:'center',dataIndex: 'maintenance_status_name', key: 'maintenance_status_name'},
  { title: '保养责任人', width: 120, align:'center',dataIndex: 'maintenance_person_name', key: 'maintenance_person_name'},
  { title: '预计用时', width: 120, align:'center',dataIndex: 'expect_time', key: 'expect_time'},
  { title: '实际用时', width: 120, align:'center',dataIndex: 'real_cost_time', key: 'real_cost_time'},
  {
    title: '操作',
    align:'center',
    key: 'operation',
    fixed: 'right',
    width: 180,
    scopedSlots: { customRender: 'action' }
  }
]

const key1Columns = [
  { title: '序号', width: 120, align:'center',dataIndex: 'id', key: 'id'},
  { title: '计划单号', width: 120, align:'center',dataIndex: 'code', key: 'code'},
  { title: '创建时间', width: 120, align:'center',dataIndex: 'create_time', key: 'create_time'},
  { title: '创建人', width: 120, align:'center',dataIndex: 'create_user_name', key: 'create_user_name'},
  { title: '计划状态', width: 120, align:'center',dataIndex: 'status_name', key: 'status_name'},
  {
    title: '操作',
    align:'center',
    key: 'operation',
    fixed: 'right',
    width: 120,
    scopedSlots: { customRender: 'action' }
  }]


const key1Data =[];

export default {
  name: "userAuthority",
  components: {PageHeadArea},
  data() {
    return {
      selectedRowKeys: [],
      record:{},
      userSearchList:[],
      tableLoading01Detail:false,
      key1DataDetail,
      key1ColumnsDetail,
      addDetailModal:false,
      planStatusList:[
        { code: 0, description: "计划中" },
        { code: 1, description: "计划完成" },
        { code: 2, description: "视情况而定" }],
      planList:[],
      planIdList: [],
      queryForm2:{
        planCode:'',
        dateSelect:[]

      },
      taskStatusList:[
        { code: 0, description: "保养中" },
        { code: 1, description: "已完成" },
        { code: 2, description: "视情况而定" }],
      deviceMaintenanceTypeList:[],
      key1Data,
      key1Columns,
      tableLoading01: false,
      axiosSource: null,
      tabKey: '1',
      title:'',
      tabBarGutter: 0,
      tabBarStyle: {
        color: 'rgba(0, 0, 0, 0.85)'
      },
      bodyStyle: {
        'padding': '0px 24px 0px 24px',
        'font-size': '14px',
        'line-height': '1.5',
        'word-wrap': 'break-word',
      },
      cardMinHeight: 0,
      queryForm: {
        code: undefined,
        name: undefined,
        status: undefined,
        dateSelect: [],
      },
      statusList: [
        // {id: 1, name: '待采购', code: '0', type: 'use_status'},
        {id: 1, name: '正常运行', code: '1',type: 'use_status'},
        {id: 2, name: '不正常运行', code: '2',type: 'use_status'},
      ],
      data,
      columns,
      pagination: {
        total: 0,
        page_size: 10,
        defaultPageSize: 10,
        page: 1,
        current: 1,
        showSizeChanger: true,
        showQuickJumper: true,
        showTotal: total => `共 ${total} 条记录`,
        pageSizeOptions: ['10', '20', '50', '100', '500'],
      },
      key1Pagination: {
        total: 0,
        page_size: 4,
        defaultPageSize: 4,
        page: 1,
        current: 1,
        showSizeChanger: true,
        showQuickJumper: true,
        showTotal: total => `共 ${total} 条记录`,
        pageSizeOptions: ['4', '8', '10', '20', '50'],
      },
      key1PaginationDetail:{
        total: 0,
        page_size: 4,
        defaultPageSize: 4,
        page: 1,
        current: 1,
        showSizeChanger: true,
        showQuickJumper: true,
        showTotal: total => `共 ${total} 条记录`,
        pageSizeOptions: ['4', '8', '10', '20', '50'],
      },
      tableLoading: false,
      addModal: false,
      canBeEdited: false, //是否可编辑
      isAdd: false, //是否为新增
      spinning: false,

      detailModal:false, //详情弹窗
      canBeQuery:false, //是否可查询

      remodelModal:false,
      maintenance_detailsModal:false,

    }
  },
  watch: {},
  authorize: {
    add: 'insert',
    getAssetLedgerList: 'query',
    reset: 'query',
    query: 'query',
    detail: 'query',
    edit: 'update',
    del: 'delete',
    check: 'check',
  },
  computed: {
    ...mapGetters(['getCardMinHeight']),
  },
  created() {
    this.cardMinHeight = this.getCardMinHeight
  },
  async mounted() {
    // this.axiosSource = axios.CancelToken.source();
    // //
    await getDeviceMaintenanceTypeList().then(res => {
      this.deviceMaintenanceTypeList = res
    })
    //
    await this.initialize()

  },
  methods: {
    onChangePage (page, pageSize) {
      this.pagination.current = page
      this.pagination.page_size = pageSize
      this.pagination.page = page
      this.initialize()
    },
    showSizeChange(current, size){
      this.pagination.page_size = size
      this.pagination.current = current
      this.pagination.page = current
      this.initialize()
    },
    onSelectChange(selectedRowKeys) {
      // console.log('selectedRowKeys changed: ', selectedRowKeys);
      this.selectedRowKeys = selectedRowKeys;
    },
    async deleteTask(record) {
      console.log(record)
      await deleteDeviceMaintenanceTask({'id': record.id})
      message.success('删除成功')

      await this.initialize()
    },
    async submitAddTask() {
      console.log(this.key1DataDetail)
      //检查
      let flag = true;
      let index = 0;

      while (flag && index < this.key1DataDetail.length) {
        if (this.key1DataDetail[index].task_code === '' || this.key1DataDetail[index].order_user_id === '' || this.key1DataDetail[index].order_user === '') {
          flag = false;
        }
        //查重
        let resSearch = await listDeviceMaintenanceTaskAll({'code':this.key1DataDetail[index].task_code})
        if(resSearch.length > 0){
          for(const codeIt of resSearch){
            if(codeIt.code === this.key1DataDetail[index].task_code){
              flag = false;
              message.error(this.key1DataDetail[index].task_code+'已重复')
              break;
            }
          }
        }

        index++;
      }
      if (flag === true) {
        for (const it of this.key1DataDetail) {
          await saveDeviceMaintenanceTask({
            'code':it.task_code,
            'plan_id':it.plan_id,
            'device_id':it.device_id,
            'maintenance_type_id':it.maintenance_type_id,
            'user_in_charge':it.order_user_id,
            'status':0
          })
        }
        message.success('新增成功')
        this.handleCancelDetail()
        //刷新
        await this.initialize()
        await this.add()
      } else {
        message.error('请填写完整信息')
      }
    },
    async deleteSelectTask() {
      for (const item of this.selectedRowKeys) {
        await deleteDeviceMaintenanceTask({'id': item});
      }
      message.success("删除成功")
      //刷新
      await this.initialize()
    },
    saveTask(){
      console.log(this.record)
      //提交
      saveDeviceMaintenanceTask({
        'id':this.record.id,
        'plan_id':this.record.plan_id,
        'device_id':this.record.device_id,
        'maintenance_type_id':this.record.maintenance_type_id,
        'user_in_charge':this.record.order_user_id,
      })

        message.success("保存成功")
      this.taskCancel()
      //更新
      this.initialize()

    },
    taskCancel(){
      this.remodelModal =false
    },
    async getUserList(order_user) {
      this.userSearchList = []
      await getCacheByVaguename(order_user).then(res=>{
        res.slice(0, 10).forEach(item => {
          this.userSearchList.push({
            id: item.id,
            name: item.name
          })
        })
      })
    },
    changeUser(item,record1){
      record1.order_user=item.name;
      record1['order_user_id'] = item.id
      // console.log(record1)
      this.userSearchList=[]
    },
    changeUser2(item){
      this.record.maintenance_person_name = item.name
      this.record.order_user_id = item.id
      this.userSearchList=[]
    },
    handleCancelDetail(){
      this.addDetailModal =false
    },
    filter2(){
      this.key1Pagination.page = 1
      this.key1Pagination.current = 1
      this.key1Pagination.page_size = 4
      this.tableLoading01 = true
      const [startDate2, endDate2] = this.queryForm2.dateSelect;

      this.key1Data= this.planList.filter(item => {
        // 检查每个条件是否满足
        return (
            (this.queryForm2.planCode ? item.code.includes(this.queryForm2.planCode) : true) &&
            (startDate2 ? new Date(item.create_time) >= new Date(startDate2) : true) &&
            (endDate2 ? new Date(item.create_time) <= new Date(endDate2) : true)
        );
      })
      this.tableLoading01 = false
    },
    async filter() {
      //筛选
      this.pagination.page = 1
      this.pagination.current = 1
      this.pagination.page_size = 10
      this.tableLoading = true
      // 获取时间范围
      const [startDate, endDate] = this.queryForm.dateSelect;
      await this.initialize()
      this.data = this.data.filter(item => {
        // 检查每个条件是否满足
        return (
            (this.queryForm.code ? item.device_code.includes(this.queryForm.code) : true) &&
            (this.queryForm.name ? item.device_name.includes(this.queryForm.name) : true) &&
            (this.queryForm.status !== undefined ? item.status === this.queryForm.status : true) &&
            (startDate ? new Date(item.maintenance_time) >= new Date(startDate) : true) &&
            (endDate ? new Date(item.maintenance_time) <= new Date(endDate) : true)
        );
      });
      this.tableLoading = false;
    },
    async initialize() {
      this.data=[]
      this.tableLoading=true

      const paramsAll = Object.assign({}, {}, {
        "page": this.pagination.page,
        "page_size": this.pagination.page_size
      });


      let planIdSet = new Set();
      await list_device_maintenance_task_all(paramsAll).then(async res => {
        if(res.data.code==='1000'){
          this.pagination.total = res.data.extension.total+(this.pagination.current-1)*this.pagination.page_size
          for (const item of res.data.data) {
            planIdSet.add(item.plan_id);
            let searchDevice = await getDeviceList({'id':item.device_id})
            item['device_code']= searchDevice[0]?.code || ''
            item['device_name']= searchDevice[0]?.name || ''

            let searchMaintenanceDate = await getMaintenancePlanDeviceRelationList({'plan_id':item.plan_id
              ,'device_id':item.device_id,'maintenance_type_id':item.maintenance_type_id})


            item['maintenance_time']= searchMaintenanceDate[0].maintenance_time
            //todo
            item['maintenance_type_name'] = this.deviceMaintenanceTypeList.find(item1 => item1.id === item.maintenance_type_id)?.name || ''
            item['maintenance_status_name'] = this.taskStatusList.find(it => it.code === item.status)?.description || ''
            //责任人
            item['maintenance_person_name'] = await getUserNameById(item.user_in_charge)
            //预计用时
            item['expect_time'] = searchMaintenanceDate[0].expect_time
            // console.log(item)
          }
        }

        this.data = res.data.data
      }).then(()=>{
        // 将 Set 转换为数组
        this.planIdList = Array.from(planIdSet);
        this.tableLoading=false
      })

    },

    callback (key) { // assetCode
      this.tabKey = key
    },
    // 分页切换
    onChange (pagination) {
      this.pagination.current = pagination.current
      this.pagination.page_size = pagination.pageSize
      this.pagination.page = pagination.current
    },
    // 分页切换
    onChangeKey1 (pagination) {
      this.key1Pagination.current = pagination.current
      this.key1Pagination.page_size = pagination.pageSize
      this.key1Pagination.page = pagination.current
    },
    onChangeKey1Detail(pagination){
      this.key1PaginationDetail.current = pagination.current
      this.key1PaginationDetail.page_size = pagination.pageSize
      this.key1PaginationDetail.page = pagination.current
    },
    async query() {
      this.pagination.page = 1
      this.pagination.current = 0
      this.pagination.page_size = 10
      this.tableLoading = true
      await this.initialize()
      this.tableLoading = false
    },
    reset() {
      this.queryForm = {
        code: '',
        name: '',
        status: undefined,
        dateSelect: [],

      }
      this.query()
    },
    detailCancel(){
      this.detailModal =false
    },
    reset2(){
      this.tableLoading01 = true
      this.queryForm2={
        planCode:'',
        dateSelect:[]
      }
      this.key1Data=this.planList
      this.tableLoading01 = false
    },
    async add() {
      this.addModal = true
      this.canBeEdited = true
      this.isAdd = true
      this.spinning = false
      //选择没有被加入task的计划
      this.planList = await getDeviceMaintenancePlanList()

      this.planList=this.planList.filter(item => !this.planIdList.includes(item.id)&& item.status === 0)
      for (const it of this.planList) {
        it['create_user_name'] = await getUserNameById(it.create_user)
        it['status_name'] = this.planStatusList.find(it2 => it2.code === it.status)?.description || ''
      }
      this.key1Data = this.planList


    },
    async addDetail(record) {
      this.addDetailModal = true
      //
      // console.log(record)
      let plan_id = record.id
      //取相关设备
      await getMaintenancePlanDeviceRelationList({'plan_id': plan_id}).then(async res => {
        for (const item of res) {
          let device_id = item.device_id
          let deviceSearch = await getDeviceList({'device_id': device_id})
          item['device_code'] = deviceSearch[0]?.code || ''
          item['device_name'] = deviceSearch[0]?.name || ''
          item['maintenance_type_name'] = this.deviceMaintenanceTypeList.find(item1 => item1.id === item.maintenance_type_id)?.name || ''
          item['order_user']=''
          item['task_code'] = ''
        }
        this.key1DataDetail = res
      })


    // console.log(this.key1DataDetail)
    },
    edit(record) {
      this.addModal = true
      this.canBeEdited = true
      this.isAdd = false
      this.echo(record)
    },
    detail(record) {
      this.detailModal = true
      this.canBeEdited = false
      this.canBeQuery =true
      this.isAdd = false
      this.echo(record)
    },
    async echo(record){
      this.record=record
    },
    remodel(record){
      this.remodelModal = true
      this.canBeEdited = true
      this.canBeQuery =true
      this.isAdd = true
      this.echo(record)
    },
    clearParameter() {},
    handleCancel() {
      this.tabKey = '1'
    },
    handleCancel0() {
      this.addModal = false
      this.canBeEdited = false
      this.isAdd = false
    },
    handleCancel1(){
      this.detailModal = false
      this.canBeEdited = false
      this.canBeQuery =false
      this.isAdd = false
    },
    submit() {

    },

  },
  beforeDestroy() {
    if (this.axiosSource) {
      this.axiosSource.cancel('Request canceled due to page navigation.');
    }
  }
}
</script>

<style scoped lang="less">

.aPopover{
}
.aPopover:hover {
  background-color: #EA5413;
}
.dataBox{
  margin-top: 20px;
}

.hide-scrollbar::-webkit-scrollbar {
  display: none; /* 隐藏滚动条 */
}

::-webkit-scrollbar {
  display: none; /* 隐藏滚动条 */
}
.hide-scrollbar {
  -ms-overflow-style: none;  /* IE 和 Edge */
  scrollbar-width: none;  /* Firefox */
  overflow-y: scroll; /* 保持内容可滚动 */
}
.demo-infinite-container {
  margin-top: 0px;
  border: 1px solid #e8e8e8;
  border-radius: 4px;
  overflow: auto;
  padding: 8px 24px;
  height: 300px;
}
/deep/ .ant-form-inline .ant-form-item-with-help{
  margin-bottom: 0px;
}
/deep/ .ant-input[disabled]{
  pointer-events: none;
  color: #000000d9;
  background-color: #f5f5f5;
  cursor: not-allowed;
  opacity: 1;
}
/deep/ .unit .ant-select-selection--single{
  margin-left: 0px;
  border-top-left-radius: 0;
  border-bottom-left-radius: 0;
  border-left: 0;
}
/deep/ .ant-select-disabled .ant-select-selection {
  background-color: #fff;
}
/deep/ .ant-input[disabled]{
  pointer-events: none;
  color: #000000d9;
  background-color: #fff;
  cursor: not-allowed;
  opacity: 1;
}
/deep/ .ant-input-number-disabled{
  pointer-events: none;
  color: #000000d9;
  background-color: #fff;
  cursor: not-allowed;
  opacity: 1;
}
</style>